package cn.sc.summer.calculate.manager;

import cn.sc.summer.calculate.po.SysTask;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 类名：
 *
 * @author a-xin
 * @date 2024/2/4 14:34
 */
@Slf4j
@Component
public class QuartzManager {

    @Resource
    private Scheduler scheduler;

    /**
     * 初始化添加任务
     *
     * @param task task任务详情
     */
    @SuppressWarnings("unchecked")
    public void addJob(SysTask task) throws Exception {
        Class<? extends Job> jobClass = (Class<? extends Job>) (Class.forName(task.getBeanClass()).newInstance().getClass());
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(task.getJobName(), task.getJobGroup())
                .build();
        // 使用cornTrigger规则
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity(task.getJobName(), task.getJobGroup())
                .startAt(DateBuilder.futureDate(1, DateBuilder.IntervalUnit.SECOND))
                .withSchedule(CronScheduleBuilder.cronSchedule(task.getCronExpression())).startNow().build();
        // 把作业和触发器注册到任务调度中
        scheduler.scheduleJob(jobDetail, trigger);
        scheduler.getListenerManager().addJobListener(new CustomJobListener());
        if (!scheduler.isShutdown()) {
            scheduler.start();
        }
    }

    /**
     * 暂停job
     *
     * @param task task任务详情
     * @throws SchedulerException 配置异常
     */
    public void pauseJob(SysTask task) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(task.getJobName(), task.getJobGroup());
        scheduler.pauseJob(jobKey);
        log.error("==> The scheduled task: {} has been paused", task.getJobName());
    }

    /**
     * 恢复执行job
     *
     * @param task task任务详情
     * @throws SchedulerException 配置异常
     */
    public void resumeJob(SysTask task) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(task.getJobName(), task.getJobGroup());
        scheduler.resumeJob(jobKey);
        log.error("==> The scheduled task: {} has been resumed", task.getJobName());
    }

    /**
     * 删除job
     *
     * @param task task任务详情
     * @throws SchedulerException 配置异常
     */
    public void deleteJob(SysTask task) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(task.getJobName(), task.getJobGroup());
        scheduler.deleteJob(jobKey);
        log.error("==> The scheduled task: {} has been delete", task.getJobName());
    }

    /**
     * 立即执行job
     *
     * @param task task任务详情
     * @throws SchedulerException 配置异常
     */
    public void runJobNow(SysTask task) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(task.getJobName(), task.getJobGroup());
        scheduler.triggerJob(jobKey);
        log.error("==> The scheduled task: {} has been run", task.getJobName());
    }

    /**
     * 执行job一次
     *
     * @param task task任务详情
     * @throws SchedulerException 配置异常
     */
    public void runJobOnce(SysTask task) throws Exception {
        JobKey jobKey = JobKey.jobKey(task.getJobName(), task.getJobGroup());
        scheduler.triggerJob(jobKey);
        log.error("==> The scheduled task: {} has been run one time", task.getJobName());
        Thread.sleep(1000);
        scheduler.pauseJob(jobKey);
    }

    /**
     * 更换job表达式
     *
     * @param task task任务详情
     * @throws SchedulerException 配置异常
     */
    public void updateJobCron(SysTask task) throws SchedulerException {
        TriggerKey triggerKey = TriggerKey.triggerKey(task.getJobName(), task.getJobGroup());
        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(task.getCronExpression());
        trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
        scheduler.rescheduleJob(triggerKey, trigger);
        log.error("==> The expression of a scheduled task:{} has been changed to {}", task.getJobName(), task.getCronExpression());
    }

}
